package com.cml.getway.core.netty;

import com.cml.getway.core.GetwayConfig;
import com.cml.getway.core.LifeCycle;
import com.cml.getway.core.helper.AsyncHttpHelper;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.EventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;

import java.io.IOException;

/**
 * 姓名：陈茂林
 * 时间：2023/12/20
 * 描述：
 */
@Slf4j
public class NettyHttpClient implements LifeCycle {
    private AsyncHttpClient asyncHttpClient;
    private GetwayConfig getwayConfig;

    private DefaultAsyncHttpClientConfig.Builder clientBuilder;

    private EventLoopGroup eventLoopGroupWork;
    public NettyHttpClient(GetwayConfig getwayConfig, EventLoopGroup eventLoopGroupWork){
        this.getwayConfig=getwayConfig;
        this.eventLoopGroupWork = eventLoopGroupWork;
        //	在构造函数调用初始化方法
        init();
    }
    @Override
    public void init() {
        this.clientBuilder = new DefaultAsyncHttpClientConfig.Builder()
                .setFollowRedirect(false)
                .setEventLoopGroup(eventLoopGroupWork)
                .setConnectTimeout(getwayConfig.getHttpConnectTimeout())
                .setRequestTimeout(getwayConfig.getHttpRequestTimeout())
                .setMaxRequestRetry(getwayConfig.getHttpMaxRequestRetry())
                .setAllocator(PooledByteBufAllocator.DEFAULT)
                .setCompressionEnforced(true)
                .setMaxConnections(getwayConfig.getHttpMaxConnections())
                .setMaxConnectionsPerHost(getwayConfig.getHttpConnectionsPerHost())
                .setPooledConnectionIdleTimeout(getwayConfig.getHttpPooledConnectionIdleTimeout());
    }

    @Override
    public void start() {
        this.asyncHttpClient = new DefaultAsyncHttpClient(clientBuilder.build());
        AsyncHttpHelper.getInstance().initialized(asyncHttpClient);
    }

    @Override
    public void shutdown() {
        if(asyncHttpClient != null) {
            try {
                this.asyncHttpClient.close();
            } catch (IOException e) {
               log.error("NettyHttpClient停止错误");
            }
        }
    }
}
